package com.tools.modules.table.service.impl;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.tools.common.utils.DateUtils;
import com.tools.common.utils.file.FileUtil;
import com.tools.generator.ConstantGen;
import com.tools.generator.config.ToolDataSource;
import com.tools.generator.entity.TableEntity;
import com.tools.generator.entity.TableFieldEntity;
import com.tools.generator.service.DataSourceService;
import com.tools.generator.service.TableService;
import com.tools.generator.utils.QueryUtils;
import com.tools.modules.table.help.TemplateUtil;
import com.tools.modules.table.service.GenFileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : ShangJY
 * @create 2024/6/2 13:50
 */
@Service("pdf")
public class PdfFileServiceImpl implements GenFileService {

    @Autowired
    private TableService tableService;

    @Autowired
    private DataSourceService dataSource;

    @Override
    public File genFile(List<Long> tableIds) throws IOException {
        // 设置模板信息
        ClassLoaderTemplateResolver templateResolver = TemplateUtil.setTemplate();

        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        List<TableEntity> tableEntity = tableService.selectTableByIds(tableIds);
        List<TableFieldEntity> fieldList = new ArrayList<>();
        tableEntity.forEach(table -> {
            ToolDataSource toolDataSource = dataSource.get(table.getDatasourceId());
            // 获取原生字段数据
            List<TableFieldEntity> tableFieldList = QueryUtils.getTableFieldList(toolDataSource, table.getId(), table.getTableName());
            fieldList.addAll(tableFieldList);
        });

        // 填充数据
        Context context = new Context();
        context.setVariable("tables", tableEntity);
        context.setVariable("data", fieldList);

        String name = DateUtils.getDateStr(DateUtils.DATE_YMDHS);
        File htmlFile = new File(ConstantGen.TEMP_DIR + ConstantGen.SEPARATOR + name + ".html");

        // 渲染模板并保存为文件
        FileWriter writer = new FileWriter(htmlFile);
        templateEngine.process("thymeleaf_pdf", context, writer);
        System.out.println("HTML 文件已生成：--->" + htmlFile.getPath());

        // 读取html 内容 生成PDF
        String htmlContent = FileUtil.readFileContent(htmlFile.getAbsolutePath());
        String pdfPath = ConstantGen.TEMP_DIR + ConstantGen.SEPARATOR+name+".pdf";
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        try {
            fontResolver.addFont("export_template/SimHei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            renderer.createPDF(Files.newOutputStream(Paths.get(pdfPath)));
            renderer.finishPDF();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        System.out.println("PDF文件已生成:"+pdfPath);

        // 删除原html todo 这样比较占性能 后续放置redis 过期删除
        FileUtils.deleteQuietly(htmlFile);
        return new File(pdfPath);
    }
}
